
<template>
  <el-dialog title="修改密码" :visible.sync="dialogFormVisible" width="500px" @close="close">
    <el-form ref="form" :model="form" :rules="rulesForm" label-position="left">
      <el-form-item label="原密码" :label-width="formLabelWidth" prop="oldPassword">
        <el-input v-model="form.oldPassword" autocomplete="off" size="small" show-password />
      </el-form-item>
      <el-form-item label="新密码" :label-width="formLabelWidth" prop="newPassword">
        <el-input v-model="form.newPassword" autocomplete="off" size="small" show-password />
      </el-form-item>
      <el-form-item label="重复密码" :label-width="formLabelWidth" prop="confirmPassword">
        <el-input v-model="form.confirmPassword" autocomplete="off" size="small" show-password />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button size="medium" @click="cancel">取 消</el-button>
      <el-button type="primary" size="medium" @click="submit">确认修改</el-button>
    </div>
  </el-dialog>
</template>
<script>
import apiUser from '@/api/user'
export default {
  name: 'Index',
  model: {
    prop: 'visible',
    event: 'close'
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      form: {
        oldPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      rulesForm: {
        oldPassword: [{
          required: true,
          message: '原密码不能为空',
          trigger: 'blur'
        }],
        newPassword: [{
          required: true,
          message: '新密码不能为空',
          trigger: 'blur'
        }, {
          min: 6,
          max: 16,
          message: '密码长度在6到16位之间',
          trigger: 'blur'
        }],
        confirmPassword: [{
          required: true,
          message: '重复密码不能为空',
          trigger: 'blur'
        }, {
          trigger: 'blur',
          validator: (rule, value, callback) => {
            if (this.form.newPassword === value) {
              callback()
            } else {
              callback(new Error('重复密码与新密码不一致'))
            }
          }
        }]
      },
      formLabelWidth: '120px'
    }
  },
  computed: {
    dialogFormVisible: {
      get() {
        return this.visible
      },
      set(val) {
        this.$emit('close', val)
      }
    }
  },
  methods: {
    close() {
      // 重置表单值
      this.$refs['form'].resetFields()
      this.dialogFormVisible = false
      // this.$emit('close', false)
    },
    submit() {
      this.$refs['form'].validate(async valid => {
        if (valid) {
          await apiUser.updatePassword(this.form)
          this.close()
        }
      })
    },
    cancel() {
      this.close()
    }
  }
}
</script>

<style scoped lang="scss">
</style>
